package com.bafa.services;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.bafa.dbcache.LeagueCache;
import com.bafa.debug.Debug;
import com.bafa.exceptions.ErrorException;
import com.bafa.exceptions.PasswordIsWrongException;
import com.bafa.exceptions.UserDoesNotExistException;
import com.bafa.front.utils.FrontUtils;
import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.objects.AdminUser;
import com.bafa.objects.User;
import com.bafa.util.PasswordUtil;

public class LogonServices {

	public static User logon(String userId)throws UserDoesNotExistException{
		DBAccess db = new DBAccess();
		try{
			
		QueryObject query = new QueryObject("users");
		query.addWhereAndField("ID","'"+userId+"'");
		ResultSet rs = db.query(query);
		if(rs.next()){
			Debug.debug(new LogonServices().getClass(), "logon",
			"Are we ok?");
			return new User(rs.getString("ID"),rs.getInt("TeamID"),rs.getString("Rights"),false);
		}else{
			throw new UserDoesNotExistException();
		}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
		
		return null;
	}
	
	
	public static User logon(String userId, String password)throws PasswordIsWrongException,UserDoesNotExistException{
		DBAccess db = new DBAccess();
		try{
			
		QueryObject query = new QueryObject("users");
		query.addWhereAndField("ID","'"+userId+"'");
		ResultSet rs = db.query(query);
		if(rs.next()){
			query.setQueryString("");
			query.addWhereAndField("Password", "'"+PasswordUtil.encrypt(password)+"'");
			
			rs = db.query(query);
			if(rs.next()){
				if(rs.getString("rights").equalsIgnoreCase("admin")){
					return new AdminUser(null,rs.getString("rights"),rs.getString("id"));
				}else{
					return new User(rs.getString("ID"),rs.getInt("TeamID"),rs.getString("Rights"),(rs.getInt("resetpassword")==1));
				}
			}else{
				throw new PasswordIsWrongException();
			}
		}else{
			throw new UserDoesNotExistException();
		}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		
	}
	
}
